package com.scs.application.modules.adm.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.consts.SerialKeys;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.flow.FlowContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UtilNum;
import com.scs.application.modules.adm.dto.MatrInquiryBidPush;
import com.scs.application.modules.adm.dto.MatrInquiryPush;
import com.scs.application.modules.adm.entity.*;
import com.scs.application.modules.adm.mapper.*;
import com.scs.application.modules.adm.service.MatrAuditService;
import com.scs.application.modules.cfg.utils.ParameterUtils;
import com.scs.application.modules.sys.adapter.FlowAdapter;
import com.scs.application.modules.sys.entity.FlowNode;
import com.scs.application.modules.thirdparty.service.MscmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 耗材准入汇总单 服务实现类
 * </p>
 *
 */
@Service
public class MatrAuditServiceImpl extends BaseServiceImpl<MatrAuditMapper, MatrAudit> implements MatrAuditService {
    @Autowired
    private MatrAuditItemServiceImpl matrAuditItemService;
    @Autowired
    private MatrApplyItemMapper matrApplyItemMapper;
    @Autowired
    private MatrApplyMapper matrApplyMapper;
    @Autowired
    private MatrInquiryTargetMapper matrInquiryTargetMapper;
    @Autowired
    private MatrInquiryResultMapper matrInquiryResultMapper;

    @Autowired
    private FlowAdapter flowAdapter;
    @Autowired
    private MscmService mscmService;
    @Override
    public boolean saveOrUpdate(MatrAudit entity) {
        if (StringUtils.isBlank(entity.getBusKey())){
            entity.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(SerialKeys.MATR_AUDIT_KEY));
        }
        return super.saveOrUpdate(entity);
    }

    /**
     * @Description：流程前校验
     */
    @Override
    protected void beforeHandleFlowChange(FlowContext flowContext, MatrAudit entity) {
        super.beforeHandleFlowChange(flowContext, entity);
        String buttonKey = flowContext.getButtonKey();
        // 提交审核，不允许空明细提交
        if ("submit".equalsIgnoreCase(buttonKey)) {
            Integer count = matrAuditItemService.count(Wrappers.<MatrAuditItem>query().eq("audit_id", flowContext.getBusId()));
            if (count == null || count == 0) {
                throw new BusinessException("请添加准入申请后，再提交");
            }
        }

        //提交询价到供应商
        if ("inquiryPush".equals(buttonKey)) {

            List<MatrApplyItem> matrApplyItems =matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("audit_id", entity.getId() ));
            if (matrApplyItems == null || matrApplyItems.size() <1) throw new BusinessException("请添加准入审批明细，再提交");
            matrApplyItems.stream().forEach(matrApplyItem -> {
                //检查询价要求，必填字段
                if (matrApplyItem.getOfficialPrice() ==null || matrApplyItem.getOfficialPrice() <= 0 ||  StringUtils.isBlank(matrApplyItem.getOfficialPriceSrc())
                || matrApplyItem.getSkuPriceMin() ==null || matrApplyItem.getSkuPriceMin() <= 0  || matrApplyItem.getSkuPriceMax()==null || matrApplyItem.getSkuPriceMax() <= 0
                ) {
                    MatrApply matrApply = matrApplyMapper.selectById(matrApplyItem.getApplyId());
                    throw new BusinessException("审批明细未设置询价要求，请检查<br>单号:%s<br>品名:%s<br>品规:%s<br>厂商:%s",
                            matrApply.getBusKey(),
                            matrApplyItem.getMatrName(),
                            matrApplyItem.getMatrSpec(),
                            matrApplyItem.getMfgName());
                }

                //检查供应商
                Integer count = matrInquiryTargetMapper.selectCount(Wrappers.<MatrInquiryTarget>query().eq("apply_item_id", matrApplyItem.getId()));
                if (count == null || count == 0) {
                    MatrApply matrApply = matrApplyMapper.selectById(matrApplyItem.getApplyId());
                    throw new BusinessException("审批明细未添加询价供应商，请检查<br>单号:%s<br>品名:%s<br>品规:%s<br>厂商:%s",
                            matrApply.getBusKey(),
                            matrApplyItem.getMatrName(),
                            matrApplyItem.getMatrSpec(),
                            matrApplyItem.getMfgName());
                }
                if (count == 1 && StringUtils.isBlank(matrApplyItem.getInquiryRemark()))    {

                    MatrApply matrApply = matrApplyMapper.selectById(matrApplyItem.getApplyId());
                    throw new BusinessException("审批明细询价供应商只有一个，请设置询价说明<br>单号:%s<br>品名:%s<br>品规:%s<br>厂商:%s",
                            matrApply.getBusKey(),
                            matrApplyItem.getMatrName(),
                            matrApplyItem.getMatrSpec(),
                            matrApplyItem.getMfgName());
                }

            });
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            //删除子表
            List<MatrAuditItem> matrAuditItems = matrAuditItemService.list(Wrappers.<MatrAuditItem>query().select("id").eq("apply_id", id));
            if (matrAuditItems != null && matrAuditItems.size() >0) {
                matrAuditItemService.removeCascadeByIds(matrAuditItems.stream().map(o -> o.getApplyId()).collect(Collectors.toList()));
            }


        }
        return super.removeCascadeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeById(Serializable id){
        return this.removeCascadeByIds(Arrays.asList(id));
    }


    /**
     * @Description：流程后处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    protected void afterHandleFlowChange(FlowContext flowContext, MatrAudit entity) {
        super.afterHandleFlowChange(flowContext, entity);

        entity = baseMapper.selectById(entity.getId());
        String flowStatus = entity.getFlowStatus();
        String buttonKey = flowContext.getButtonKey();
        boolean endBid = false;
        switch (buttonKey){
            case "inquiryPush": //询价单推送

                //询价主单
                MatrInquiryPush matrInquiryPull = new MatrInquiryPush();
                BeanUtils.copyProperties(entity,matrInquiryPull);
                matrInquiryPull.setRefId(entity.getId());

                //询价明细

                List<MatrApplyItem> matrApplyItems =matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("audit_id", entity.getId() ));

                //询价供应商列表
                List<MatrInquiryTarget> matrInquiryTargets =matrInquiryTargetMapper.selectList(Wrappers.<MatrInquiryTarget>query().eq("audit_id", entity.getId() ));

                List<MatrInquiryPush.MatrInquiryItemPush>  matrInquiryItemPulls=new ArrayList<MatrInquiryPush.MatrInquiryItemPush>();
                matrApplyItems.stream().forEach(matrApplyItem -> {
                    MatrInquiryPush.MatrInquiryItemPush matrInquiryItemPull = new MatrInquiryPush.MatrInquiryItemPush();
                    BeanUtils.copyProperties(matrApplyItem,matrInquiryItemPull);
                    matrInquiryItemPull.setManufacturerName(matrApplyItem.getMfgName());
                    matrInquiryItemPull.setDeliveryAddress(matrApplyItem.getDeliverAddress());
                    matrInquiryItemPull.setMaterialName(matrApplyItem.getMatrName());
                    matrInquiryItemPull.setCatalogId(matrApplyItem.getCategoryId());
                    matrInquiryItemPull.setCatalogName(matrApplyItem.getCategoryName());
                    matrInquiryItemPull.setRefId(matrApplyItem.getAuditItemId());
                    matrInquiryItemPull.setMaterialSpec(matrApplyItem.getMatrSpec());
                    matrInquiryItemPull.setCertificateNo(matrApplyItem.getCertificateNo());
                    matrInquiryItemPull.setSunpurchaseCode(matrApplyItem.getSunpurchaseCode());

                    //询价明细供应商名字列表
                    List<String> supplierNames =  matrInquiryTargets.stream().filter(matrInquiryTarget ->matrInquiryTarget.getApplyItemId().equals(matrApplyItem.getId()) )
                            .map(MatrInquiryTarget::getSupplierName).collect(Collectors.toList());
                    matrInquiryItemPull.setSupplierNames(supplierNames);

                    matrInquiryItemPulls.add(matrInquiryItemPull);
                });


                //询价供应商列表
                List<MatrInquiryPush.MatrInquirySpItemPush> supplierItems = new ArrayList<MatrInquiryPush.MatrInquirySpItemPush>();
                matrInquiryTargets.stream().forEach(matrInquiryTarget -> {
                    MatrInquiryPush.MatrInquirySpItemPush matrInquirySpItemPull = new MatrInquiryPush.MatrInquirySpItemPush();
                    BeanUtils.copyProperties(matrInquiryTarget,matrInquiryTarget);
                    matrInquirySpItemPull.setContactor(matrInquiryTarget.getSupplierContactor());
                    matrInquirySpItemPull.setMobile(matrInquiryTarget.getSupplierTel());
                    matrInquirySpItemPull.setName(matrInquiryTarget.getSupplierName());
                    supplierItems.add(matrInquirySpItemPull);
                });

                matrInquiryPull.setInquiryItems(matrInquiryItemPulls);
                matrInquiryPull.setSupplierItems(supplierItems);
                flowContext.setHandledMsg(mscmService.admInquiryPush(matrInquiryPull));
                break;
            case "inquiryEnd": //结束询价
                flowContext.setHandledMsg(mscmService.admInquiryEnd(entity.getId()));
                break;
            case "inquiryContinue": //进行院内评审
                //拉取报价信息
                flowContext.setHandledMsg("已进行院内评审，"+mscmService.admInquiryPull(entity.getId()).getMsg());
                break;
            case "fuyuanzhang": //副院长审批
                double admAuditMax = UtilNum.getDouble(ParameterUtils.getString("adm_audit_max"));
                if (admAuditMax <=0) {
                    throw new BusinessException("系统缺少重要参数【准入审批限额adm_audit_max】，请联系运营人员配置");
                }
                List<MatrApplyItem> matrApplyItems2 =matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("audit_id", entity.getId() ));
                double priceSum = matrApplyItems2.stream().mapToDouble(MatrApplyItem::getSkuPrice).sum();
                //如果审批金额小于限制金额，则直接审核通过，
                if (priceSum <= admAuditMax) {
                    endBid = true;
                    entity.setFlowStatus("end");
                    MatrAudit matrAudit = new MatrAudit();
                    matrAudit.setId(entity.getId());
                    baseMapper.update(matrAudit,Wrappers.<MatrAudit>update().eq("id",entity.getId()).set("flow_status","end"));
                }
                break;
        }
        //流程结束时，推送中标结果
        if (GlobalConsts.FLOW_END_VALUE.equals(flowStatus) || endBid) {
            //拉取报价信息
            mscmService.admInquiryPull(entity.getId());

//            如果没有任何报价信息，就不推送了
            Integer count = matrInquiryResultMapper.selectCount(Wrappers.<MatrInquiryResult>query().eq("audit_id", flowContext.getBusId()));
            if (count == null || count == 0) {
                flowContext.setHandledMsg("耗材准入成功，无供应商报表，故未添加新的耗材");
                return;
            }

            MatrInquiryBidPush matrInquiryBidPush = new MatrInquiryBidPush();
            matrInquiryBidPush.setRefId(entity.getId());

            //中标明细
            List<MatrApplyItem> matrApplyItems =matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("audit_id", entity.getId() ));
            List<MatrInquiryBidPush.Item>  matrInquiryItemPulls=new ArrayList<MatrInquiryBidPush.Item>();
            matrApplyItems.stream().forEach(matrApplyItem -> {
                if (StringUtils.isBlank(matrApplyItem.getSupplierName())) {
                    throw new BusinessException("审批明细未设置中标供应商，请检查<br>品名:%s<br>品规:%s<br>厂商:%s",
                            matrApplyItem.getMatrName(),
                            matrApplyItem.getMatrSpec(),
                            matrApplyItem.getMfgName());
                }
                MatrInquiryBidPush.Item item = new MatrInquiryBidPush.Item();
                item.setSkuOfficialPrice(matrApplyItem.getSkuPricePurchase());
                item.setSkuOfficialPriceSrc(matrApplyItem.getSkuOfficialPriceSrc());
                item.setItemRefId(matrApplyItem.getAuditItemId());
                item.setSupplierCode(matrApplyItem.getSupplierCode());
                item.setSupplierName(matrApplyItem.getSupplierName());
                item.setApplyItemId(matrApplyItem.getId());
                item.setSkuPricePurchase(matrApplyItem.getSkuPricePurchase());
                item.setSkuPriceSell(matrApplyItem.getSkuPriceSell());
                matrInquiryItemPulls.add(item);
            });
            matrInquiryBidPush.setItems(matrInquiryItemPulls);

            flowContext.setHandledMsg("耗材准入成功，"+mscmService.admInquiryBId(matrInquiryBidPush));
        }

        //更新关联的申请单明细状态
        List<MatrApplyItem> matrApplyItems = matrApplyItemMapper.selectList(Wrappers.<MatrApplyItem>query().eq("audit_id", entity.getId() ));

        FlowNode flowNode = flowAdapter.getFlowNodeService().getByFlowIdAndValue(flowContext.getFlow().getId(), entity.getFlowStatus());
        matrApplyItems.forEach(matrApplyItem -> {
            //更新准入申请单明细所关联的审核明细
            MatrApplyItem matrApplyItemUpdate = new MatrApplyItem();
            matrApplyItemMapper.update(matrApplyItemUpdate,Wrappers.<MatrApplyItem>update()
                    .eq("id",matrApplyItem.getId())
                    .set("audit_flow_status_text",flowNode.getName())
            );
        });
    }


}
